package com.qyhl.module_practice.volunteer.list;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeIsVolunteerBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeVolunteerBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

public class PracticeVolunteerFragment extends BaseFragment implements PracticeVolunteerContract.PracticeVolunteerView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.search_btn)
    TextView searchBtn;
    @BindView(R2.id.search_txt)
    TextView searchTxt;
    @BindView(R2.id.top_layout)
    RelativeLayout topLayout;

    private String orgId;

    private int page = 1;

    private int searchPage = 1;

    private boolean isSearchModel = false;

    private boolean isVolunteer;

    private View view;

    private String keyword = "";

    private String instId;


    private CommonAdapter commonAdapter;

    private List<PracticeVolunteerBean> mDataList = new ArrayList<>();

    private List<PracticeVolunteerBean> indexList = new ArrayList<>();


    public void setVolunteer(boolean volunteer) {
        isVolunteer = volunteer;
    }

    public void setInstId(String instId) {
        this.instId = instId;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    private PracticeVolunteerPresenter mPresenter;

    public static PracticeVolunteerFragment newInstance(boolean isVolunteer, String instId, String orgId) {
        PracticeVolunteerFragment fragment = new PracticeVolunteerFragment();
        fragment.setVolunteer(isVolunteer);
        fragment.setInstId(instId);
        fragment.setOrgId(orgId);
        return fragment;
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true,0.2f)
                .statusBarColor(R.color.white)
                .fitsSystemWindows(true)
                .init();
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.practice_fragment_volunteer, null);
    }

    @Override
    protected void create() {
        mPresenter = new PracticeVolunteerPresenter(this);
        loadData();
    }



    @Override
    protected void setListener() {
        setListeners();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    /**
     * 加载数据
     */
    private void loadData() {
        //下拉刷新
        initView();
        setListener();
        if (StringUtils.isEmpty(orgId)) {
            mPresenter.getList(page + "");
        } else {
            mPresenter.getOrgList(orgId, page + "");
        }
    }


    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        BusFactory.getBus().register(this);
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        if (StringUtils.isEmpty(orgId)) {
            orgId = "";
        }

        if (isVolunteer) {
            bottomLayout.setVisibility(View.GONE);
        } else {
            bottomLayout.setVisibility(View.VISIBLE);
        }

        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeVolunteerBean>(getContext(), R.layout.practice_item_volunteer, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeVolunteerBean bean, int position) {
                ImageView cover = holder.getView(R.id.cover);
                Glide.with(getContext().getApplicationContext())
                        .load(bean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                        .into(cover);

                holder.setText(R.id.name, bean.getName());

                holder.setText(R.id.subject, bean.getServiceNums() + "");

                holder.setText(R.id.score, bean.getTotalScore() + "");

                holder.setText(R.id.time, DateUtils.PracticeServiceTimeFormat(bean.getServiceTimes()));


                if (bean.getOrgs() != null && bean.getOrgs().size() > 0) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < bean.getOrgs().size(); i++) {
                        if (i == 0) {
                            stringBuilder.append(bean.getOrgs().get(i).getName());
                        } else {
                            stringBuilder.append(",").append(bean.getOrgs().get(i).getName());
                        }

                    }
                    holder.setText(R.id.service_team, stringBuilder.toString());
                    holder.setVisible(R.id.service_layout, true);
                } else {
                    holder.setText(R.id.service_team, "无");
                    holder.setVisible(R.id.service_layout, false);
                }

                holder.setVisible(R.id.level_tag, true);
                switch (bean.getLevel()) {
                    case 0:
                        holder.setVisible(R.id.level_tag, false);
                        break;
                    case 1:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv1_icon);
                        break;
                    case 2:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv2_icon);
                        break;
                    case 3:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv3_icon);
                        break;
                    case 4:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv4_icon);
                        break;
                    case 5:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv5_icon);
                        break;
                }
            }

        });
    }

    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                if (isSearchModel) {
                    searchPage = 1;
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.doSearch(keyword, searchPage + "");
                    } else {
                        mPresenter.doOrgSearch(keyword, searchPage + "", orgId);
                    }

                } else {
                    page = 1;
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.getList(page + "");
                    } else {
                        mPresenter.getOrgList(orgId, page + "");
                    }
                }
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (isSearchModel) {
                    searchPage = 1;
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.doSearch(keyword, searchPage + "");
                    } else {
                        mPresenter.doOrgSearch(keyword, searchPage + "", orgId);
                    }
                } else {
                    page = 1;
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.getList(page + "");
                    } else {
                        mPresenter.getOrgList(orgId, page + "");
                    }
                }
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isSearchModel) {
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.doSearch(keyword, searchPage + "");
                    } else {
                        mPresenter.doOrgSearch(keyword, searchPage + "", orgId);
                    }
                } else {
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.getList(page + "");
                    } else {
                        mPresenter.getOrgList(orgId, page + "");
                    }
                }
            }
        });


        searchTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyword = s.toString();
                if (StringUtils.isNotEmpty(s.toString()) && s.toString().trim().length() > 0) {
                    searchBtn.setText("搜索");
                } else {
                    searchBtn.setText("取消");
                }
            }
        });

        searchTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//按下搜索
                    keyword = searchTxt.getText().toString();
                    searchPage = 1;
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.doSearch(keyword, searchPage + "");
                    } else {
                        mPresenter.doOrgSearch(keyword, searchPage + "", orgId);
                    }
                    hideInput();
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }

        });
    }

    @Override
    public void setList(List<PracticeVolunteerBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        indexList.clear();
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        indexList.addAll(mDataList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setSearchList(List<PracticeVolunteerBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        searchPage++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setIsVolunteer(PracticeIsVolunteerBean bean) {
        if (bean != null) {
            if (bean.getVolId() == 0) {
                bottomLayout.setVisibility(View.VISIBLE);
            } else {
                switch (bean.getStatus()) {
                    case "PASS":
                        bottomLayout.setVisibility(View.GONE);
                        break;
                    case "NOT_VERIFY":
                        bottomLayout.setVisibility(View.GONE);
                        break;
                    case "NOT_PASS":
                        bottomLayout.setVisibility(View.VISIBLE);
                        break;
                    case "DEL":
                        bottomLayout.setVisibility(View.VISIBLE);
                        break;
                }
            }
        } else {
            bottomLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setError(String msg, boolean isMore) {
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！", 4);
            } else if (msg.contains("暂无")) {
                showToast("暂无更多志愿者！", 4);
            } else {
                showToast(msg, 4);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }


    @OnClick({R2.id.search_btn, R2.id.become_btn, R2.id.search_delete})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.search_btn) {
            if (searchBtn.getText().toString().equals("搜索")) {
                if (StringUtils.isNotEmpty(keyword)) {
                    isSearchModel = true;
                    searchPage = 1;
                    if (StringUtils.isEmpty(orgId)) {
                        mPresenter.doSearch(keyword, searchPage + "");
                    } else {
                        mPresenter.doOrgSearch(keyword, searchPage + "", orgId);
                    }
                } else {
                    showToast("搜索内容不能为空！", 4);
                }
            } else {
                if (indexList != null && indexList.size() > 0) {
                    loadMask.setStatus(LoadingLayout.Success);
                }
                isSearchModel = false;
                searchPage = 1;
                mDataList.clear();
                mDataList.addAll(indexList);
                commonAdapter.notifyDataSetChanged();
            }
        } else if (id == R.id.become_btn) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", "");
                        bundle.putBoolean("isVolunteer", true);
                        bundle.putString("instId", instId);
                        RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER_SIGN,bundle);
                    } else {
                        Toasty.normal(getContext(), "尚未登录或登录失效！").show();
                        RouterManager.routerLogin(getActivity(), 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });
        } else if (id == R.id.search_delete) {
            searchTxt.setText("");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.PracticeActRefresh event) {
        if (event != null) {
            bottomLayout.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                //登录
                String userName = CommonUtils.getInstance().getUserName();
                mPresenter.getIsVolunteer(userName);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }


}
